import EventEmitter from 'events'
import dispatcher from './dispatcher'

class Store extends EventEmitter {
  constructor() {
    super()
    this._state = []

    dispatcher.register(action => {
      const {actionType, payload} = action

      switch(actionType) {
        case 'add':
          this._add(payload)
          break
        case 'getList':
          this._getList(payload)
          break
        case 'remove':
          this._remove(payload)
          break
      }
    })
  }

  _getList(data) {
    this._state = data
    this.emit('change', this._state)
  }

  _add(item) {
    this._state.push(item)
    this.emit('change', this._state)
  }

  remove(id) {
    const index = this._state.findIndex(item => item === id)
    index > -1 && this._state.splice(index, 1)
    this.emit('change', this._state)
  }

  get state() {
    return this._state
  }
}

export default Store